package com.wn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wn.bean.DataRoles;
import com.wn.bean.R;
import com.wn.bean.RolePermission;
import com.wn.mapper.RolePermissionMapper;
import com.wn.service.IRolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yellow Docter
 * @since 2022-05-16
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 修改操作 
     * @param map
     * @return
     *
     * (rid=2, ids=[4, 5])
     * 前端的新的权限
     *
     * 01通过rid 把之前的权限 都删除
     *
     * 02 通过 ids 和rid 添加 权限
     *
     */
    @Override
    @Transactional //添加事务
    public R updatePermission(DataRoles dataRoles) {

        // 通过主键删除 role_permission 没有主键 没法删除
//        rolePermissionMapper.deleteById()
        // 条件对象
        Integer rid = dataRoles.getRid();
        QueryWrapper<RolePermission> qr = new QueryWrapper<>();
        qr.eq("rid",rid);
        int delete = rolePermissionMapper.delete(qr);

        if(delete <= 0 ){
            throw new RuntimeException();
        }

        //02 通过 ids 和rid 添加 权限

        // 批处理的方法是   ServiceImpl 的父类方法 可以直接调用
        // 可以添加集合的操作

        List<RolePermission> rolePermissions =new ArrayList<>();

        // (rid=2, ids=[4, 5])  ids=4, 5 权限
        List<Integer> ids = dataRoles.getIds();
        for (Integer id : ids) {
            rolePermissions.add(new RolePermission(rid,id));
        }

        boolean b = saveBatch(rolePermissions);

        if (!b){
            throw new RuntimeException();
        }
        return R.OK("修改成功");
    }
}
